import '@nutui/nutui-react-taro/dist/style.css'
import { Component } from 'react'
import Taro from '@tarojs/taro'
import { transmitFormData } from './network/servers'
import { Provider } from 'react-redux'
import configStore from './store'
import { HttpGet } from './network/servers'
import './app.scss'
import Utils from './utils'
import { getStorage } from './pages/components/utils'
import {setStyle,getColor } from 'lancoo-ui-mobile'

const store = configStore()
const storage = getStorage()

console.log(store);

interface WeapApp {
  state: StateType;
}

class WeapApp extends Component {

  constructor(props) {
    super(props)
  }

  loginParams = {//登陆页面所需参数
    systemID: '260',
    systemName: '日程安排',
    appID: 'wx3b4f698c5833a431',
    systemIconUrl: './images/login-logo.png',//路径以pages>>wxLogin页面为当前路径
    isAfterUserLogout: false,
    loginSucUrl: 'pages/scheduleApp/index'//登陆成功后跳转的页面
  }
  checkTokenTimer
  systemInfo = null
  isIPhoneX = false
  phoneType = 6
  homePageHeight = 0
  navigationBarHeight = 0
  tabbarHeight = 0
  screenHeight = 0
  screenWidth = 0
  naviHomeHeight = 0
  statusBarHeight = 0
  isFristLanch = false
  assetSystemUrl = null
  gradeSystemUrl = null
  gradeWebSystemUrl = null
  dormSystemUrl = null
  paySystemUrl = null
  attendSystemUrl = null
  attendFaceSystemUrl = null
  appID = "wx9e4895714e80e3f1"
  isUserLogout = false
  isLogin = false
  paymentSystem = { systemId: 'E81' }
  publicKeyOfPay = null
  globalData = {
    userInfo: null,
    localuserInfo: null,
    userName: null,
    userType: null,
    userID: null,
    realUserID: null,
    Token: null,
    loginInfo: null,
    schoolLevel: 0,
    schoolID: null,
    schoolUrl: null,
    schoolName: null,
    phoneType: 6,
    loginParam: null,
    Psw: null,
    unionID: null,
    openID: null,
    classID: "",
    groupID: '',
    isLogin: false,
    termInfo: "2019-202002",
    gender: null,
    curSubsystemUrl: '',
    curSubsystemInfo: null,
    localSchoolID: null,
    code: null,
  }

  /**
    * 显示success日志
    */
  showToastSuccess = (message) => {
    Taro.showToast({
      title: message,
      icon: 'success',
      duration: 2000
    })
  }
  /**
   * 显示错误日志
   */
  showToastError = (message) => {
    Taro.showToast({
      title: message,
      icon: 'none',
      duration: 2000
    })
  }

  showLoading = (text = '请稍后', mask) => {
    if (mask) {
      Taro.showLoading({
        title: text,
        mask: mask,
      });
    } else {
      Taro.showLoading({
        title: text,
        mask: false,
      });
    }
  }

  hideLoading = () => {
    Taro.hideLoading()
  }
  //更新Token
  refreshToken = () => {
    this.checkTokenTimer = setInterval(() => {
      this.checkToken();
    }, 2000);
  }

  //清除Timer
  clearTimer = () => {
    clearInterval(this.checkTokenTimer);
  }
  //检查Token是否失效
  checkToken = () => {//必须走校园通的formData转发接口，因为data是formData类型的，而且微信不提供formData的格式
    var that = this;
    var paramData = {
      AppID: that.appID,
      Param: JSON.stringify({
        token: that.globalData.Token,
        method: "TokenCheck",
        params: "E43",
      }),
      SchoolID: that.globalData.schoolID,
      Url: that.globalData.schoolUrl + "/UserMgr/Login/Api/Login.ashx",
      UserID: that.globalData.userID,
    };

    transmitFormData(paramData).then((data) => {
      var dataInfo = JSON.parse(data.data.Content);
      if (!dataInfo.data.result) {
        console.log("Token失效了，开始重新更新Token");
        that.userRelogin();
      } else {
        console.log("万幸,Token还活着");
      }
    });
  }

  getReLoginMap = (password) => {//必须走校园通的formData转发接口，因为data是formData类型的，而且微信不提供formData的格式
    var app = this;
    var params = app.globalData.userID + "|" + password + "|E43|" + app.globalData.phoneType + "|||";
    let strMap = JSON.stringify({
      method: "Login",
      params: params
    })
    return strMap;
  }
  userRelogin = () => {
    var that = this;
    var paramString = that.getReLoginMap(that.globalData.Psw);
    var paramData = {
      AppID: that.appID,
      Param: paramString,
      SchoolID: that.globalData.schoolID,
      Url: that.globalData.schoolUrl + "/UserMgr/Login/Api/Login.ashx",
      UserID: that.globalData.userID,
    };

    transmitFormData(paramData).then((data) => {
      if (data.data.Content) {
        try {
          var dataInfo = JSON.parse(data.data.Content);
          if (dataInfo.data.result == 1) {
            that.globalData.Token = dataInfo.data.token;
            console.log("已重新获取Token,新token:" + dataInfo.data.token);
            clearInterval(that.checkTokenTimer);
            that.refreshToken();
          } else {
            console.log("重新获取Token失败");
          }
        } catch (error) { }
      } else {
        console.log("后台错误了");
      }
    });
  }


  componentDidMount() {
    setStyle()
    const getSysWeb = (params, type = 'web', func) => {
    console.log(params, 'params');

      let url = '', data = {}
      if (process.env.TARO_ENV === 'h5' && Utils.getQueryVariable('env') !== 'weapp') {
        url = `api/common/system/info`
      } else {
        url = 'https://campus.lancooedu.com/school/getSubsystemBySystemId'
        data = {
          systemId: params.sysId,
          schoolId: params.schoolId
        }
      }
      //web为web地址，ws为socket地址
      HttpGet({
        url,
        data,
      }).then((result) => {
        if (result.code === '200') {
          storage.set('productType', result.data.productType);
          storage.set('productUseRange', result.data.productUseRange);
          storage.set('webName', result.data.webName);
          storage.set('baseUrl', result.data.baseUrl);
          storage.set('itemUrl', result.data.itemUrl);
          storage.set('sysId', result.data.sysId);
          this.setState({
            sysId: result.data.sysId
          })
          //获取用户信息
          let url = `/api/common/user`
          HttpGet({
            url,
            data,
          }).then((result) => {
            if (result.code === '200') {
              storage.set('schoolId', result.data.schoolId);
              storage.set('schoolLevel', result.data.schoolLevel);
              storage.set('schoolName', result.data.schoolName);

              // let url = `/api/common/locker/inside/check`
              let url = 'api/commons/locker/check'
              data = {
                sysId: this.state.sysId,
                lockerId: 171,
                schoolId: result.data.schoolId,
              }
              HttpGet({
                url,
                data,
              }).then((result) => {
                if (result.code === '200') {
                  let url = `/api/common/system/list`
                  data = {
                    sysIds: this.state.sysId,
                  }
                  HttpGet({
                    url,
                    data,
                  }).then((result) => {
                    if (result.code === '200') {
                      let baseUrl = result.data[0].webSvrAddr;
                      if (Utils.getSystemInfo() === 'h5') {
                        if (type === 'web') {
                          func(baseUrl)
                        } else {
                          func(baseUrl)
                        }
                      } else {
                        func(baseUrl)
                      }
                    }
                  })
                }
              })
            }
          })
        } else {
          Taro.showToast({
            title: result.msg || '请求出错',
            icon: 'none',
            duration: 2500,
            mask: true
          })
        }
      })
    }
    Taro.getSysWeb = getSysWeb
  }

  componentDidShow() {
  }

  componentDidHide() { }

  componentDidCatchError() { }

  // this.props.children 是将要会渲染的页面
  render() {
    return (
      <Provider store={store}>
        {this.props.children}
      </Provider>
    )
  }
}

type StateType = {
  sysId: any;
}

interface App {
  state: StateType;
}

class App extends Component {

  constructor(props) {
    super(props)
    this.state = {
      sysId: '',
    }
  }

  componentDidMount() {
    setStyle()
    const getSysWeb = (params, type = 'web', func) => {
      let url = '', data = {}
      if (Utils.getSystemInfo() === 'h5') {
        url = `api/common/system/info`,
          data = {
            token: Utils.getQueryVariable('lg_tk') || storage.get('token')
          }
        //web为web地址，ws为socket地址
        HttpGet({
          url,
          data,
        }).then((result) => {
          // console.log(result, 'result');
          if (result.code === '200' || result.error == 0) {
            storage.set('productType', result.data.productType);
            storage.set('productUseRange', result.data.productUseRange);
            storage.set('webName', result.data.webName);
            storage.set('baseUrl', result.data.baseUrl);
            storage.set('itemUrl', result.data.itemUrl);
            storage.set('sysId', result.data.sysId);
            this.setState({
              sysId: result.data.sysId
            })
            //获取用户信息
            let url = `/api/common/user`
            HttpGet({
              url,
              data,
            }).then((result) => {
              if (result.code === '200') {
                storage.set('schoolId', result.data.schoolId);
                storage.set('schoolLevel', result.data.schoolLevel);
                storage.set('schoolName', result.data.schoolName);

                // let url = `/api/common/locker/inside/check`
                let url = 'api/commons/locker/check'
                data = {
                  sysId: this.state.sysId,
                  lockerId: 171,
                  schoolId: result.data.schoolId,
                }
                HttpGet({
                  url,
                  data,
                }).then((result) => {
                  if (result.code === '200') {
                    let url = `/api/common/system/list`
                    data = {
                      sysIds: this.state.sysId,
                    }
                    HttpGet({
                      url,
                      data,
                    }).then((result) => {
                      if (result.code === '200') {
                        let baseUrl = result.data[0].webSvrAddr;
                        // console.log(baseUrl, 'baseUrl');
                        if (Utils.getSystemInfo() === 'h5') {
                            func(baseUrl)
                        } else {
                          func(baseUrl)
                        }
                      }
                    })
                  }
                })
              }
            })

          } else {
            Taro.showToast({
              title: result.msg || '请求出错',
              icon: 'none',
              duration: 2500,
              mask: true
            })
          }
        })
      } else {
      console.log(params, 'params');
        
        url = 'https://campus.lancooedu.com/school/getSubsystemBySystemId'
        data = {
          systemId: params.sysId,
          schoolId: params.schoolId || Utils.getQueryVariable('schoolId'),
        }
        HttpGet({
          url,
          data,
        }).then((result) => {
          if (result.error === 0) {
            let baseUrl = result.data.url;
            if (Utils.getSystemInfo() === 'h5') {
              func(baseUrl)
            } else {
              func(baseUrl)
            }
          }
        })
      }

    }

    Taro.getSysWeb = getSysWeb
  }

  componentDidShow() { }

  componentDidHide() { }

  componentDidCatchError() { }

  // this.props.children 是将要会渲染的页面
  render() {
    return (
      <Provider store={store}>
        {this.props.children}
      </Provider>
    )
  }
}


function getApp() {
  return Taro.getEnv() == Taro.ENV_TYPE.WEAPP ? WeapApp : App
}


export default getApp()
